package controller;

import com.alibaba.fastjson.JSONObject;
import utils.MD5UsingMessageDigest;
import utils.UserManager;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;

@WebServlet("/forget")
public class Forget extends HttpServlet {

    private static final Logger logger = Logger.getLogger(Forget.class.getName());

    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {

        String email = req.getParameter("email");
        String password = req.getParameter("password");
        JSONObject resJson = new JSONObject();

        try {
            // 验证邮箱和密码参数
            if (email == null || email.trim().isEmpty()) {
                resJson.put("status", "error");
                resJson.put("message", "邮箱不能为空");
            } else if (password == null || password.trim().isEmpty()) {
                resJson.put("status", "error");
                resJson.put("message", "密码不能为空");
            } else if (password.length() < 6) {
                resJson.put("status", "error");
                resJson.put("message", "密码长度不能少于6位");
            } else {
                // 检查用户是否存在
                boolean exist = UserManager.userExists(email);
                if (!exist) {
                    resJson.put("error", "email");
                    resJson.put("status", "error");
                    resJson.put("message", "用户不存在");
                } else {
                    // 更新用户密码
                    UserManager.updateUserPassword(email, MD5UsingMessageDigest.md5(password));
                    resJson.put("status", "success");
                    resJson.put("message", "密码更新成功");
                }
            }
        } catch (Exception e) {
            logger.log(Level.SEVERE, "Error processing forget password request", e);
            resJson.put("status", "error");
            resJson.put("message", "服务器错误");
        }

        resp.setContentType("application/json;charset=utf-8");
        resp.getWriter().print(resJson.toJSONString());
    }
}